package com.oazon.common.util.curcity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;

import com.moco.launcher.listener.CloudListener;
import com.oazon.common.util.RequestManager;

public class AddressUtil {

	private static final String TAG = "AddressUtil";

	/**
	 * 根据ip得到当前城市
	 * 
	 * @param ctx
	 * @param callback
	 */
	public static void getCurCityName(final Context ctx,
			final AddressCallback callback) {

		AddressCallback ipCallback = new AddressCallback() {

			@Override
			public void onSuccess(String str) {
				requestCityName(str, ctx, callback);
			}

			@Override
			public void onError(String er) {
				if (callback != null) {
					callback.onError(er);
				}
			}
		};
		getCurrentIp(ctx, ipCallback);

	}

	private static void requestCityName(String ip, Context ctx,
			final AddressCallback callback) {

		String url = "http://apistore.baidu.com/microservice/iplookup?ip=" + ip;

		RequestManager.sendRequest(ctx, url, new CloudListener() {
			
			@Override
			public void onResponse(String response) {
				if (callback != null) {
					callback.onSuccess(response);
				}
				
			}
			
			@Override
			public void onError(int err, String msg) {
				if (callback != null) {
					callback.onError(msg);
				}
				
			}
		});
	}

	/**
	 * 得到当前所在的ip
	 * 
	 * @param ctx
	 * @param callback
	 */
	public static void getCurrentIp(Context ctx, final AddressCallback callback) {

		String url = "http://1111.ip138.com/ic.asp";
		RequestManager.sendRequest(ctx, url, new CloudListener() {
			
			@Override
			public void onResponse(String response) {
				String ipTemp = "";
				String ip = "";
				String regexT = "\\[\\d.*\\]";
				Pattern paT = Pattern.compile(regexT);
				Matcher maT = paT.matcher(response);
				if (maT.find()) {
					ipTemp += maT.group();
				}

				String regex = "[\\d.*]";
				Pattern pa = Pattern.compile(regex);
				Matcher ma = pa.matcher(ipTemp);
				while (ma.find()) {
					ip += ma.group();
				}
				if (callback != null) {
					callback.onSuccess(ip);
				}
			}
			
			@Override
			public void onError(int err, String msg) {
				if (callback != null) {
					callback.onError(msg);
				}
				
			}
		});
	}

}
